package com.sinosoft.service;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.sinosoft.domain.Account;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author loujiang
 * @date 2021/1/2 2:38 下午
 * @NOTE:
 */
@Slf4j
@Service
public class JwtService {

    //生产环境请不要使用这种方式 配置在配置文件中且加密过后的数据
    private static final String KEY = "keyword";
    private static final String ISSUER = "sam";

    private static final String USERNAME = "username";
    private static final long TOKEN_EXP_TIME = 60000;

    /**
     * 生成token
     * @param account
     * @return
     */
    public String token(Account account) {
        Date now = new Date();
        Algorithm algorithm = Algorithm.HMAC256(KEY);
        String token = JWT.create().withIssuer(ISSUER).withIssuedAt(now)
                .withExpiresAt(new Date(now.getTime() + TOKEN_EXP_TIME))
                .withClaim(USERNAME, account.getUsername()).sign(algorithm);

        log.info("jwt generated user={}", account.getUsername());
        return token;
    }

    /**
     * 校验token
     * @param token
     * @param username
     * @return
     */
    public boolean verify(String token, String username) {
        log.info("verifying jwt - username={}", username);
        try {
            Algorithm algorithm = Algorithm.HMAC256(KEY);
            JWTVerifier verifier = JWT.require(algorithm).
                    withIssuer(ISSUER).withClaim(USERNAME,username).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {

            log.error("auth failed", e);
            return false;
        }
    }
}
